//
//  977_有序数组的平方.swift
//  Swift-LeetCode
//
//  Created by 卢悦明 on 2024/3/8.
/**
 给你一个按 非递减顺序 排序的整数数组 nums，返回 每个数字的平方 组成的新数组，要求也按 非递减顺序 排序。

 示例 1：
 输入：nums = [-4,-1,0,3,10]
 输出：[0,1,9,16,100]
 解释：平方后，数组变为 [16,1,0,9,100]
 排序后，数组变为 [0,1,9,16,100]
 
 示例 2：
 输入：nums = [-7,-3,2,3,11]
 输出：[4,9,9,49,121]
 */

import UIKit

class ArrayPingFang: NSObject {
    func QA()  {
        print(sortedSquares([-4,-1,0,3,10]))
        print(sortedSquares([-7,-3,2,3,11]))
        print(sortedSquares([1,2,3,4,5]))


    }
    func sortedSquares(_ nums: [Int]) -> [Int] {
        var zeroIndex = -1
        for (index, item) in nums.enumerated() {
            if item < 0 {
                zeroIndex = index
            } else {
                break
            }
        }

        var leftIndex = zeroIndex
        var rightIndex = zeroIndex + 1
        var array = Array(repeating: 0, count: nums.count)
        var index = 0
        while leftIndex >= 0 || rightIndex < nums.count {
            if leftIndex < 0 {
                array[index] = nums[rightIndex] * nums[rightIndex]
                rightIndex += 1
            } else if rightIndex == nums.count {
                array[index] = nums[leftIndex] * nums[leftIndex]
                leftIndex -= 1
            } else{
                let left = nums[leftIndex] * nums[leftIndex]
                let right =  nums[rightIndex] * nums[rightIndex]
                if left > right {
                    array[index] = right
                    rightIndex += 1
                } else {
                    array[index] = left
                    leftIndex -= 1
                }
            }
            index += 1
        }
        return array
    }
}
